package com.fofia.iotweb.web.domain.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.fofia.iotweb.web.domain.dto.SmartTagDto;
import com.fofia.iotweb.web.domain.mappers.SmartTagDtoMapper;
import com.fofia.iotweb.web.domain.mappers.SmartTagMapper;
import com.fofia.iotweb.web.domain.models.SmartTag;
import com.fofia.iotweb.web.dto.DataTableDto;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.DbChain;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.row.RowUtil;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.dynamicds.DynamicDs;
//import com.mybatisflex.core.row.Db as DbFlex;
import java.util.ArrayList;
import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.avg;

@Component
public class SmartTagService {

    @Inject("tag")
    private SmartTagMapper _smartTagMapper;
    @Inject("tag")
    private SmartTagDtoMapper _smartTagDtoMapper;

    /**
     * 分页列表，包含总记录数total
     * @param tagId
     * @param page
     * @param psize
     * @param startTime
     * @param endTime
     * @return
     */
    public DataTableDto getPageList(String tagId,String gatewayId, int page, int psize, String startTime, String endTime,int inTime){
        String tableName= StrUtil.format("t_{}",new  Object[]{tagId});
        DataTableDto  dto=new DataTableDto();
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.from(tableName);
        queryWrapper.where("upload_time > '"+startTime+"' and upload_time <'"+endTime+"'");
        if(!StrUtil.isEmpty(gatewayId)){
            queryWrapper.where("gateway_id='"+gatewayId+"'");
        }
        if(inTime==1){
            queryWrapper.where("record_id=0");
        }
        queryWrapper.orderBy("upload_time desc");
        //String sql=queryWrapper.toSQL();
        //System.out.println(sql);
        Page<SmartTag> records=_smartTagMapper.paginate(page,psize,queryWrapper);
        var list=records.getRecords();
        for(SmartTag tag : list) {
            tag.setTagId(tagId);
            int sportFixTime=tag.getSportTime()-tag.getIntenseSport()-tag.getSport();
            tag.setSportFixTime(sportFixTime);
        }
        dto.setRows(list);
        dto.setTotal(records.getTotalRow());
        dto.setPageNumber(page);
        dto.setPageSize(psize);

        return dto;
    }

    /**
     * 历史数据，按时间升序
     * @param tagId 标签id
     * @param page  页码
     * @param psize 每页数量
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public List<SmartTag> getHistoryList(String tagId,String gatewayId, int page, int psize, String startTime, String endTime,int inTime){
        String tableName= StrUtil.format("t_{}",new  Object[]{tagId});
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.from(tableName);
        queryWrapper.where("upload_time > '"+startTime+"' and upload_time <'"+endTime+"'");
        if(!StrUtil.isEmpty(gatewayId)){
            queryWrapper.where("gateway_id='"+gatewayId+"'");
        }
        if(inTime==1){
            queryWrapper.where("record_id=0");
        }
        queryWrapper.orderBy("upload_time");
        queryWrapper.limit((page-1)*psize,psize);
        //String sql=queryWrapper.toSQL();
        //System.out.println(sql);
        List<SmartTag> list=_smartTagMapper.selectListByQuery(queryWrapper);
        //Page<FcData> list=_fcdataMapper.paginate(page,psize,queryWrapper);
        for(SmartTag tag : list) {
            tag.setTagId(tagId);
            int sportFixTime=tag.getSportTime()-tag.getIntenseSport()-tag.getSport();
            tag.setSportFixTime(sportFixTime);
        }
        return list;
    }

     /**
     *历史数据，按时间降序
     * @param tagId 标签id
     * @param page  页码
     * @param psize 每页数量
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public List<SmartTag> getHistoryDescList(String tagId,String gatewayId, int page, int psize, String startTime, String endTime,int inTime){
        String tableName= StrUtil.format("t_{}",new  Object[]{tagId});
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.from(tableName);
        queryWrapper.where("upload_time > '"+startTime+"' and upload_time <'"+endTime+"'");
        if(!StrUtil.isEmpty(gatewayId)){
            queryWrapper.where("gateway_id='"+gatewayId+"'");
        }
        if(inTime==1){
            queryWrapper.where("record_id=0");
        }
        queryWrapper.orderBy("upload_time desc");
        queryWrapper.limit((page-1)*psize,psize);
        //String sql=queryWrapper.toSQL();
        //System.out.println(sql);
        List<SmartTag> list=_smartTagMapper.selectListByQuery(queryWrapper);
        //Page<FcData> list=_fcdataMapper.paginate(page,psize,queryWrapper);
        for(SmartTag tag : list) {
            tag.setTagId(tagId);
            int sportFixTime=tag.getSportTime()-tag.getIntenseSport()-tag.getSport();
            tag.setSportFixTime(sportFixTime);
        }
        return list;
    }

    /**
     *  根据时间窗口获取活跃时长
     * @param tagId
     * @param startTime
     * @param endTime
     * @param interval
     * @return
     */
    public List<SmartTag> getIntervalList(String tagId,String fieldName, String startTime, String endTime,String interval){
        String tableName=StrUtil.format("t_{}",tagId);
         String sqlWhere=StrUtil.format("upload_time > '{}' and upload_time<'{}' {}",startTime,endTime,interval);
        String sqlField=StrUtil.format("last_row({}) as {},upload_time",fieldName,fieldName);
        QueryWrapper queryWrapper=QueryWrapper.create()
                        .select(sqlField)
                        .from(tableName)
                        .where(sqlWhere);
        //StaticLog.info(queryWrapper.toSQL());
        List<SmartTag> list=_smartTagMapper.selectListByQuery(queryWrapper);
        return list;
    }

    /**
     *  根据时间窗口获取活跃时长
     * @param tagId
     * @param startTime
     * @param endTime
     * @param interval
     * @return
     */
    @DynamicDs("tag") //使用 db_user 动态源内的 db_user_1 源
    public List<Row> getIntervalListByRow(String tagId,String fieldName, String startTime, String endTime,String interval){
        String tableName=StrUtil.format("t_{}",tagId);
        String sqlWhere=StrUtil.format("upload_time > '{}' and upload_time<'{}' {}",startTime,endTime,interval);
        String sqlField=StrUtil.format("last_row({}) as {},upload_time",fieldName,fieldName);

        //StaticLog.info(queryWrapper.toSQL());
        //List<SmartTagDto> rows = DbChain.table(tableName).select(sqlField).where(sqlWhere).listAs(SmartTagDto.class);
        List<Row> rows = DbChain.table(tableName).select(sqlField).where(sqlWhere).list();
//        QueryWrapper queryWrapper=QueryWrapper.create()
//                .select(sqlField)
//                .from(tableName)
//                .where(sqlWhere);
//        //StaticLog.info(queryWrapper.toSQL());
//        List<SmartTagDto> list=_smartTagDtoMapper.selectListByQuery(queryWrapper);
//        return list;
         StaticLog.info("row count:{}",rows.size());
         return rows;
    }



    /**
     *  根据时间窗口获取活跃时长
     * @param tagId
     * @param startTime
     * @param endTime
     * @param interval
     * @return
     */
    public List<SmartTag> getIntervalListAll(String tagId, String startTime, String endTime,String interval){

       // List<SmartTag> list=new ArrayList<>();
        List<SmartTag> sportTime=getIntervalList(tagId,"sport_time",startTime,endTime,interval);
        List<SmartTag> FeedTime=getIntervalList(tagId,"sport",startTime,endTime,interval);
        List<SmartTag> ruminateTime=getIntervalList(tagId,"ruminate_time",startTime,endTime,interval);

        //循环sportTime
        int len=sportTime.size();

        for(int i=0;i<len;i++){
            SmartTag tag=sportTime.get(i);
            tag.setSport(FeedTime.get(i).getSport());
            tag.setRuminateTime(ruminateTime.get(i).getRuminateTime());
        }
        return sportTime;
    }

    /**
     * 查询数据按照时间范围平均温度
     * @param tagId
     * @param startTime
     * @param endTime
     * @return
     */
    public int  getAvgTemperature(String tagId,String startTime, String endTime){
        String tableName= StrUtil.format("t_{}",new  Object[]{tagId});
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.select(avg("temperature")).as("temperature");
        queryWrapper.from(tableName);
        queryWrapper.where("upload_time > '"+startTime+"' and upload_time <'"+endTime+"'");
        float temperature=_smartTagMapper.selectOneByQueryAs(queryWrapper, Float.class);
        return (int)temperature;
    }
    /**
     *
     * 查询数据按照时间范围
     * @param tagId
     * @param startTime
     * @param endTime
     * @return
     */
    public int getCountByTime (String tagId,String startTime, String endTime){
        String tableName= StrUtil.format("t_{}",new  Object[]{tagId});
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.from(tableName);
        queryWrapper.where("upload_time > '"+startTime+"' and upload_time <'"+endTime+"'");
        long count=_smartTagMapper.selectCountByQuery(queryWrapper);
        return (int)count;
    }




    /**
     *  根据时间窗口获取活跃时长
     * @param tagId
     * @param startTime
     * @param endTime
     * @param interval
     * @return
     */
    public List<SmartTag> getLastListByHour(String tagId,String startTime, String endTime){
        List<SmartTag> list=new ArrayList<>();
        DateTime stime= new DateTime(startTime, DatePattern.NORM_DATETIME_FORMAT);
        DateTime etime=new DateTime(endTime, DatePattern.NORM_DATETIME_FORMAT);
        int index=0;
         while (true){

             DateTime stime1= DateUtil.offsetHour(stime, index);
             long betweenDay = DateUtil.compare(stime1, etime);
             if(betweenDay>=0){
                 break;
             }
             DateTime etime1= DateUtil.offsetHour(stime1, 1);
             //StaticLog.info("开始时间：{},结束时间:{}",stime1.toString(),etime1.toString());
             List<SmartTag> model=getHistoryDescList(tagId,"",1,1,stime1.toString(),etime1.toString(),0);
              if(model.size()==1){
                  SmartTag tag=model.get(0);
                  int sportFixTime=tag.getSportTime()-tag.getIntenseSport()-tag.getSport();
                  tag.setSportFixTime(sportFixTime);
                  list.add(tag);
              }
             index++;
         }


        return list;
    }
}
